﻿namespace FormStateKeeper
{
    using System;
    using System.Web;
    using System.Web.Caching;

    /// <summary>
    /// Form state storage provider using Http cache.
    /// </summary>
    public class HttpCacheFormStateStorage : IFormStateStorageProvider
    {
        private static readonly TimeSpan StateCacheDuration = TimeSpan.FromMinutes(30);

        /// <summary>
        /// Initializes a new instance of the <see cref="HttpCacheFormStateStorage"/> class.
        /// </summary>
        public HttpCacheFormStateStorage()
        {
        }

        #region IFormStateStorageProvider Members

        /// <summary>
        /// Stores the form state using the http cache.
        /// </summary>
        /// <param name="formState">The form state to store.</param>
        public void Store(FormState formState)
        {
            HttpRuntime.Cache.Add(
                "FormStateSaver_" + formState.StateId,
                formState,
                null,
                Cache.NoAbsoluteExpiration,
                StateCacheDuration,
                CacheItemPriority.Normal,
                null);
        }

        /// <summary>
        /// Retrieves the form state from the http cache.
        /// </summary>
        /// <param name="id">Id of form state to retrieve.</param>
        /// <returns>The retrieved form state</returns>
        public FormState Retrieve(string id)
        {
            return HttpRuntime.Cache["FormStateSaver_" + id] as FormState;
        }

        /// <summary>
        /// Deletes the form state from the http cache.
        /// </summary>
        /// <param name="id">The id of the form state to delete.</param>
        public void Delete(string id)
        {
            HttpRuntime.Cache.Remove("FormStateSaver_" + id);
        }

        #endregion
    }
}
